package com.easonji.core.shiro;

import com.easonji.admin.model.User;
import com.easonji.common.util.StringUtils;
import com.easonji.core.shiro.factory.ShiroFactory;
import com.easonji.core.shiro.factory.ShiroFactroyImpl;
import com.easonji.core.shiro.util.ShiroUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @ClassName: ShiroDbRealm
 * @Description:自定义的Realm
 * @Author: LiuJun
 * @date: 2018/07/10 10:00
 * @Version: 1.0
 * @Copyright: Copyright (c) 2018 - 2019
 */
public class ShiroDbRealm extends AuthorizingRealm {

    /**
     * 验证用户身份
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
            throws AuthenticationException {
        ShiroFactory shiroFactory = ShiroFactroyImpl.me();
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        User user = shiroFactory.user(token.getUsername());
        ShiroUser shiroUser = shiroFactory.shiroUser(user);
        SimpleAuthenticationInfo info = shiroFactory.info(shiroUser, user, super.getName());
        return info;
    }

    /**
     * 授权访问控制
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        ShiroFactory shiroFactory = ShiroFactroyImpl.me();
        ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
        Set<String> permissionSet = new HashSet<>();
        List<String> permissions = shiroFactory.findPermissionsByRoleIds(shiroUser.getRoleIds());
        if (permissions != null) {
            for (String permission : permissions) {
                if (StringUtils.isNotEmpty(permission)) {
                    permissionSet.add(permission);
                }
            }
        }
        Set<String> roleNameSet = new HashSet<>();
        List<String> roleNames = shiroUser.getRoleNames();
        for (String roleName : roleNames) {
            roleNameSet.add(roleName);
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(permissionSet);
        info.addRoles(roleNameSet);
        return info;
    }

    /**
     * 设置认证加密方式
     */
    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        HashedCredentialsMatcher md5CredentialsMatcher = new HashedCredentialsMatcher();
        md5CredentialsMatcher.setHashAlgorithmName(ShiroUtils.HASH_ALGORITHM_NAME);
        md5CredentialsMatcher.setHashIterations(ShiroUtils.HASH_ITERATIONS);
        super.setCredentialsMatcher(md5CredentialsMatcher);
    }
}
